package com.mei.offer;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 输入一个链表，从尾到头打印链表每个节点的值
 * 链表 tmd 不是 jdk 里面的玩意...所以这里自定义了下
 */
public class Test5 {

    public static void main(String[] args) {
        ListNode listNode = buildListNode();
        System.out.println(listNode);

        System.out.println(printListFromTailToHead(listNode));
    }

    private static List<Integer> printListFromTailToHead(ListNode listNode) {

        if (null == listNode) {
            return null;
        }

        Stack<Integer> stack = new Stack<>();
        while (null != listNode) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }

        List<Integer> list = new ArrayList<>();
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }

        return list;
    }


    private static ListNode buildListNode() {
        ListNode node1 = new ListNode(1);

        ListNode node2 = new ListNode(2);
        node1.next = node2;

        ListNode node3 = new ListNode(3);
        node2.next = node3;

        ListNode node4 = new ListNode(4);
        node3.next = node4;

        node4.next = new ListNode(5);

        return node1;
    }


    public static class ListNode {

        int val;

        ListNode next;

        ListNode(int val) {
            this.val = val;
        }

        @Override
        public String toString() {
            return "ListNode{" + "val=" + val + ", next=" + next + '}';
        }
    }

}

